package com.example.smartgreenhouse.exception;

import com.example.smartgreenhouse.utils.ResponseWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<ResponseWrapper<?>> handleBusinessException(BusinessException ex) {

        // 根据异常信息判断返回状态码
        if (ex.getMessage().contains("没有生效")) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ResponseWrapper.failure(404, ex.getMessage()));
        }
        return ResponseEntity.badRequest()
                .body(ResponseWrapper.badRequest(ex.getMessage()));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ResponseWrapper<?>> handleGlobalException(Exception ex) {
        log.error("全局异常捕获 >>> 类型: {} 信息: {}",
                ex.getClass().getName(),
                ex.getMessage(),
                ex); // 打印完整堆栈
        return ResponseEntity.internalServerError()
                .body(ResponseWrapper.failure(500, "系统繁忙，请稍后再试"));
    }

}